package com.example.sixthproject_server;

import android.os.Handler;
import android.os.Message;
import android.support.annotation.BinderThread;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
import butterknife.BindView;
import butterknife.ButterKnife;


//增加注释
public class MainActivity extends AppCompatActivity {

    @BindView(R.id.main_content) TextView main_content;
    Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 0x1234) {
                    main_content.setText(main_content.getText().toString() + msg.getData().getString("content"));
                }
            }
        };
        new Thread(new UdpServer(handler)).start();
    }
}

class UdpServer implements Runnable {
    private final static int localPort = 5000;
    byte[] buf = new byte[1024];
    Handler handler;
    DatagramSocket localDs = null;

    public UdpServer(Handler handler) {
        this.handler = handler;
        try {
            localDs = new DatagramSocket(localPort);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true) {
            try {
                DatagramPacket localDp = new DatagramPacket(buf, 1024);
                localDs.receive(localDp);
                String rec = new String(localDp.getData(), localDp.getOffset(), localDp.getLength());
                Message msg = new Message();
                msg.what = 0x1234;
                Bundle bundle = new Bundle();
                bundle.putString("content", rec);
                msg.setData(bundle);
                handler.sendMessage(msg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
